<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.7.2/css/all.min.css" integrity="sha256-dABdfBfUoC8vJUBOwGVdm8L9qlMWaHTIfXt+7GnZCIo=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"blog.csgrandeur.cn","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.22.0","exturl":false,"sidebar":{"position":"left","width_expanded":320,"width_dual_column":240,"display":"post","padding":18,"offset":12},"hljswrap":true,"copycode":{"enable":true,"style":"default"},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"duration":200,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"top_n_per_article":1,"unescape":false,"preload":false,"trigger":"auto"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="动态规划入门  动态（Dynamic）：问题的解因时间或决策而变化 规划（Programming）：分解子问题，利用子问题之间关系求解">
<meta property="og:type" content="article">
<meta property="og:title" content="26.动态规划入门">
<meta property="og:url" content="http://blog.csgrandeur.cn/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/index.html">
<meta property="og:site_name" content="CSGrandeur&#39;s Thinking">
<meta property="og:description" content="动态规划入门  动态（Dynamic）：问题的解因时间或决策而变化 规划（Programming）：分解子问题，利用子问题之间关系求解">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E6%95%B0%E5%AD%97%E4%B8%89%E8%A7%92%E5%BD%A2_%E4%BB%80%E4%B9%88%E6%98%AF%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92.svg">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E6%95%B0%E5%AD%97%E4%B8%89%E8%A7%92%E5%BD%A2_%E7%BC%96%E5%8F%B7.svg">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92_%E9%80%92%E6%8E%A8%E4%B8%8E%E9%80%92%E5%BD%92.svg">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/DAG.svg">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E7%9F%A9%E5%BD%A2%E5%B5%8C%E5%A5%97_%E5%BB%BADAG.svg">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E7%9F%A9%E9%98%B5%E9%93%BE_%E6%9C%80%E5%90%8E%E4%B9%98%E6%B3%95%E4%BD%8D%E7%BD%AE.svg">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E8%83%8C%E5%8C%85_%E5%AE%8C%E5%85%A8%E8%83%8C%E5%8C%85.svg">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E8%83%8C%E5%8C%85_01%E8%83%8C%E5%8C%85.svg">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E6%9C%80%E9%95%BF%E4%B8%8A%E5%8D%87%E5%AD%90%E5%BA%8F%E5%88%97.svg">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E6%9C%80%E9%95%BF%E4%B8%8A%E5%8D%87%E5%AD%90%E5%BA%8F%E5%88%97_%E5%B0%BE%E5%85%83%E7%B4%A0%E5%BA%8F%E5%88%97.svg">
<meta property="article:published_time" content="2025-04-16T06:51:01.000Z">
<meta property="article:modified_time" content="2025-04-24T05:07:09.478Z">
<meta property="article:author" content="CSGrandeur">
<meta property="article:tag" content="ACM">
<meta property="article:tag" content="Algorithm">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://blog.csgrandeur.cn/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E6%95%B0%E5%AD%97%E4%B8%89%E8%A7%92%E5%BD%A2_%E4%BB%80%E4%B9%88%E6%98%AF%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92.svg">


<link rel="canonical" href="http://blog.csgrandeur.cn/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/">


<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://blog.csgrandeur.cn/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/","path":"2025-04-16-26-动态规划入门/","title":"26.动态规划入门"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>26.动态规划入门 | CSGrandeur's Thinking</title>
  

  <script src="/js/third-party/analytics/baidu-analytics.js"></script>
  <script async src="https://hm.baidu.com/hm.js?7958adf931092425a489778560129144"></script>







  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">CSGrandeur's Thinking</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">Cogito Ergo Sum</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
      <div class="search-header">
        <span class="search-icon">
          <i class="fa fa-search"></i>
        </span>
        <div class="search-input-container">
          <input autocomplete="off" autocapitalize="off" maxlength="80"
                placeholder="搜索..." spellcheck="false"
                type="search" class="search-input">
        </div>
        <span class="popup-btn-close" role="button">
          <i class="fa fa-times-circle"></i>
        </span>
      </div>
      <div class="search-result-container">
        <div class="search-result-icon">
          <i class="fa fa-spinner fa-pulse fa-5x"></i>
        </div>
      </div>
    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8"><span class="nav-number">1.</span> <span class="nav-text">动态规划入门</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%80%92%E6%8E%A8%E4%B8%8E%E5%B8%A6%E5%A4%87%E5%BF%98%E9%80%92%E5%BD%92"><span class="nav-number">1.1.</span> <span class="nav-text">递推与带备忘递归</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9C%89%E5%90%91%E6%97%A0%E7%8E%AF%E5%9B%BEdp"><span class="nav-number">1.2.</span> <span class="nav-text">有向无环图DP</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B%E7%9F%A9%E5%BD%A2%E5%B5%8C%E5%A5%97"><span class="nav-number">1.2.1.</span> <span class="nav-text">例：矩形嵌套</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8C%BA%E9%97%B4dp"><span class="nav-number">1.3.</span> <span class="nav-text">区间DP</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B%E6%8B%AC%E5%8F%B7%E5%8C%B9%E9%85%8D"><span class="nav-number">1.3.1.</span> <span class="nav-text">例：括号匹配</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B%E7%9F%A9%E9%98%B5%E9%93%BE%E4%B9%98%E6%B3%95"><span class="nav-number">1.3.2.</span> <span class="nav-text">例：矩阵链乘法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%83%8C%E5%8C%85dp"><span class="nav-number">1.4.</span> <span class="nav-text">背包DP</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B%E5%AE%8C%E5%85%A8%E8%83%8C%E5%8C%85"><span class="nav-number">1.4.1.</span> <span class="nav-text">例：完全背包</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B01%E8%83%8C%E5%8C%85"><span class="nav-number">1.4.2.</span> <span class="nav-text">例：01背包</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BA%BF%E6%80%A7%E7%BB%93%E6%9E%84dp"><span class="nav-number">1.5.</span> <span class="nav-text">线性结构DP</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B%E6%9C%80%E9%95%BF%E4%B8%8A%E5%8D%87%E5%AD%90%E5%BA%8F%E5%88%97"><span class="nav-number">1.5.1.</span> <span class="nav-text">例：最长上升子序列</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B%E6%9C%80%E9%95%BF%E5%85%AC%E5%85%B1%E5%AD%90%E5%BA%8F%E5%88%97"><span class="nav-number">1.5.2.</span> <span class="nav-text">例：最长公共子序列</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%B6%E5%AE%83dp%E5%89%8D%E7%9E%BB"><span class="nav-number">1.6.</span> <span class="nav-text">其它DP前瞻</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%8A%B6%E6%80%81%E5%8E%8B%E7%BC%A9dp"><span class="nav-number">1.6.1.</span> <span class="nav-text">状态压缩DP</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%95%B0%E4%BD%8Ddp"><span class="nav-number">1.6.2.</span> <span class="nav-text">数位DP</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%A0%91%E5%BD%A2dp"><span class="nav-number">1.6.3.</span> <span class="nav-text">树形DP</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%BD%AE%E5%BB%93%E7%BA%BFdp%E6%8F%92%E5%A4%B4dp"><span class="nav-number">1.6.4.</span> <span class="nav-text">轮廓线DP（插头DP）</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">CSGrandeur</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">72</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">22</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://blog.csgrandeur.cn/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="CSGrandeur">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="CSGrandeur's Thinking">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="26.动态规划入门 | CSGrandeur's Thinking">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          26.动态规划入门
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2025-04-16 14:51:01" itemprop="dateCreated datePublished" datetime="2025-04-16T14:51:01+08:00">2025-04-16</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2025-04-24 13:07:09" itemprop="dateModified" datetime="2025-04-24T13:07:09+08:00">2025-04-24</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/ACM/" itemprop="url" rel="index"><span itemprop="name">ACM</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/ACM/ACMCOURSE/" itemprop="url" rel="index"><span itemprop="name">ACMCOURSE</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><h1 id="动态规划入门">动态规划入门</h1>
<ul>
<li>动态（Dynamic）：问题的解因时间或决策而变化</li>
<li>规划（Programming）：分解子问题，利用子问题之间关系求解</li>
</ul>
<span id="more"></span>
<h2 id="递推与带备忘递归">递推与带备忘递归</h2>
<p>数字三角形：从顶部出发，只能沿箭头走，到底部的哪个路线经过的所有数字之和最大</p>
<img src="/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E6%95%B0%E5%AD%97%E4%B8%89%E8%A7%92%E5%BD%A2_%E4%BB%80%E4%B9%88%E6%98%AF%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92.svg" class="">
<p>给每个格子编号</p>
<style>.qtxljvdcgezx{height: 300px;}</style>
<img src="/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E6%95%B0%E5%AD%97%E4%B8%89%E8%A7%92%E5%BD%A2_%E7%BC%96%E5%8F%B7.svg" class="qtxljvdcgezx" title="给每个格子编号">
<p>思考 2 件事：</p>
<ol type="1">
<li><p><strong>最优子结构</strong>：数学化定义问题，分析该问题哪些更小规模的子问题的解可以直接影响它的解</p>
<ul>
<li>定义 <span class="math inline">\(d(i,j)\)</span> 是从 <span
class="math inline">\((i,j)\)</span> 出发到底的最大和</li>
<li>可知 <span class="math inline">\(d(1,1)\)</span> 是问题的最优解</li>
<li><span class="math inline">\(d(i,j)\)</span> 与 <span
class="math inline">\(d(i+1,j)\)</span>、<span
class="math inline">\(d(i+1,j+1)\)</span> 直接相关——有这俩就能确定 <span
class="math inline">\(d(i,j)\)</span></li>
</ul></li>
<li><p><strong>状态转移方程</strong>：对于特定规模的问题，能直接影响它的子问题以什么方式计算能推导到它</p>
<ul>
<li>设 <span class="math inline">\(a(i,j)\)</span> 是 <span
class="math inline">\((i,j)\)</span> 格子的值</li>
<li><span
class="math inline">\(d(i,j)=a(i,j)+\max(d(i+1,j),d(i+1,j+1))\)</span></li>
</ul></li>
</ol>
<p>动态规划的两种等价实现方法，渐进复杂度通常一致</p>
<img src="/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92_%E9%80%92%E6%8E%A8%E4%B8%8E%E9%80%92%E5%BD%92.svg" class="" title="动态规划递推与递归">
<p><strong>自底向上的递推</strong></p>
<p>从小到大逐个解决子问题</p>
<p>优势：没有频繁的递归调用，常数更小</p>
<p>劣势：思维量——需要预先确定好子问题规模大小，即求解的顺序</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">DP</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> j = <span class="number">1</span>; j &lt;= n; j ++) dp[n][j] = a[n][j];</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = n - <span class="number">1</span>; i &gt;= <span class="number">1</span>; i --)    <span class="comment">// 自底向上递推</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="type">int</span> j = <span class="number">1</span>; j &lt;= i; j ++)</span><br><span class="line">            dp[i][j] = std::<span class="built_in">max</span>(dp[i + <span class="number">1</span>][j], dp[i + <span class="number">1</span>][j + <span class="number">1</span>]) + a[i][j];</span><br><span class="line">    <span class="keyword">return</span> dp[<span class="number">1</span>][<span class="number">1</span>];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>自顶向下的带备忘递归</strong>（记忆化搜索）</p>
<p>对需要但尚未解决的子问题进行递归求解，否则直接返回备忘</p>
<p>优势：</p>
<ol type="1">
<li>思维量相对小，直接按状态转移方程实现</li>
<li>有的特殊情况下能跳过很多子问题</li>
</ol>
<p>劣势：递归开销，甚至面对有些过大的问题没有足够的递归栈</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">DPS</span><span class="params">(<span class="type">int</span> i, <span class="type">int</span> j)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(i &gt; n) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    <span class="type">int</span> &amp;ans = dp[i][j];</span><br><span class="line">    <span class="keyword">if</span>(ans != <span class="number">-1</span>) <span class="keyword">return</span> ans;</span><br><span class="line">    ans = std::<span class="built_in">max</span>(<span class="built_in">DPS</span>(i + <span class="number">1</span>, j), <span class="built_in">DPS</span>(i + <span class="number">1</span>, j + <span class="number">1</span>)) + a[i][j];</span><br><span class="line">    <span class="keyword">return</span> ans;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="有向无环图dp">有向无环图DP</h2>
<img src="/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/DAG.svg" class="" title="有向无环图">
<p>有向无环图（Directed Acyclic
Graph，DAG）是指不存在环的有向图，从任意点出发沿有向边走，不会再回到该点。</p>
<p>很多动态规划问题可以转换为DAG上的最长/最短路或路径计数。</p>
<h3 id="例矩形嵌套">例：矩形嵌套</h3>
<p>给出一系列矩形的长和宽，矩形𝐴能够嵌套在𝐵内部当且仅当𝐴的长与宽都对应严格小于𝐵的长与宽，求这些矩形能够组成的最深嵌套</p>
<p>构建DAG：</p>
<img src="/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E7%9F%A9%E5%BD%A2%E5%B5%8C%E5%A5%97_%E5%BB%BADAG.svg" class="" title="矩形嵌套建DAG">
<p><strong>最优子结构</strong>：</p>
<ul>
<li>"可嵌套"关系可以建模为图：<span class="math inline">\((i,j)\in
E\)</span>表示<span class="math inline">\(j\)</span>能嵌套在<span
class="math inline">\(i\)</span>内，有向边<span
class="math inline">\(i\rightarrow j\)</span>，该图是DAG</li>
<li><span class="math inline">\(d(i)\)</span>表示<span
class="math inline">\(i\)</span>为最外层时的最深嵌套，只与<span
class="math inline">\((i,j)\in E\)</span>的<span
class="math inline">\(j\)</span>有关</li>
</ul>
<p><strong>状态转移方程</strong>：</p>
<ul>
<li><span class="math inline">\(d(i)=\max\{d(j)+1|(i,j)\in
E\}\)</span></li>
</ul>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">DPS</span><span class="params">(<span class="type">int</span> i)</span> </span>&#123;</span><br><span class="line">    <span class="type">int</span> &amp;ans = dp[i];</span><br><span class="line">    <span class="keyword">if</span>(ans != <span class="number">-1</span>) <span class="keyword">return</span> ans;</span><br><span class="line">    ans = <span class="number">1</span>;    <span class="comment">// 至少包含自身</span></span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> j = <span class="number">1</span>; j &lt;= n; j ++) </span><br><span class="line">        <span class="keyword">if</span>(g[i][j] &amp;&amp; <span class="built_in">DPS</span>(j) + <span class="number">1</span> &gt; ans)&#123;</span><br><span class="line">            ans = <span class="built_in">DPS</span>(j) + <span class="number">1</span>; </span><br><span class="line">        &#125; </span><br><span class="line">    <span class="keyword">return</span> ans;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>思考：如果不止要求最深嵌套层数，还要求把最深嵌套的各个节点按顺序输出，怎么做？</p>
<p>提示：状态转移时记录转移方向</p>
<p>复杂度分析：</p>
<p>要填一个<code>dp[]</code>，有<span
class="math inline">\(O(n)\)</span>项。每一项要一个<span
class="math inline">\(O(n)\)</span>的循环才能得到最终结果，所以<span
class="math inline">\(O(n^2)\)</span>。</p>
<blockquote>
<p>知识点：动态规划的复杂度分析技巧。动态规划就是一个"填表游戏"，其复杂度就由表的大小和完成表的每一项最坏情况的复杂度决定。</p>
</blockquote>
<p>扩展题：有<span
class="math inline">\(n\)</span>种立方体（每种数量无限），选一些堆成尽可能高的柱子，上方的立方体底面长宽必须严格小于下方的立方体。</p>
<p>提示：立方体可以任选一个棱作为高，则另外两个棱构成底面长宽。</p>
<h2 id="区间dp">区间DP</h2>
<h3 id="例括号匹配">例：括号匹配</h3>
<p>给定一个只包含<code>&#123;&#125;</code>、<code>()</code>、<code>[]</code>的字符串
括号嵌套可能不合法，如"<code>&#123;(] )</code>"
给出添加符号最少的方案，使括号嵌套合法</p>
<p><strong>最优子结构</strong>：</p>
<ul>
<li><span class="math inline">\(d(i,j)\)</span> 表示 <span
class="math inline">\([i, j]\)</span>
这段符号的最优解，即最少添加使之合法的方案</li>
<li>可以从 3 个方向转移
<ul>
<li>左边加一个让 <span class="math inline">\(j\)</span> 匹配</li>
<li>右边加一个让 <span class="math inline">\(i\)</span> 匹配，</li>
<li>如果<span class="math inline">\(i\)</span>和<span
class="math inline">\(j\)</span>位置恰好匹配，那么不用加，让它俩匹配</li>
</ul></li>
</ul>
<p><strong>状态转移方程</strong>：</p>
<ul>
<li><span class="math inline">\(d(i,j)=\begin{cases} \min(d(i+1,j-1),
d(i+1,j)+1, d(i,j-1)+1) &amp; \text{如果}s[i]\text{和}s[j]\text{匹配} \\
\min(d(i+1,j)+1, d(i,j-1)+1) &amp; \text{否则} \end{cases}\)</span></li>
</ul>
<h3 id="例矩阵链乘法">例：矩阵链乘法</h3>
<blockquote>
<p>还没学过线性代数的同学，可以简单了解下<strong>矩阵是什么，如何相乘</strong>：</p>
<ul>
<li>两个矩阵相乘，则第一个的列数必须等于第二个的行数，比如第一个 <span
class="math inline">\(a\times b\)</span>，第二个必须 <span
class="math inline">\(b\times c\)</span></li>
<li>矩阵相乘的结果是第一个的行数、第二个的列数，即<span
class="math inline">\(a\times b\)</span> 和 <span
class="math inline">\(b\times c\)</span> 两个矩阵相乘得到 <span
class="math inline">\(a \times c\)</span></li>
<li>相乘方式：结果矩阵的 <span class="math inline">\((i,j)\)</span>
位置的值，是前一个的第 <span class="math inline">\(i\)</span>
行与后一个的第 <span class="math inline">\(j\)</span>
列一一对应相乘再加起来的结果</li>
</ul>
<p><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> x[a][b], y[b][c], z[a][c];</span><br><span class="line"><span class="comment">// ...</span></span><br><span class="line"><span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; a; i ++) &#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> j = <span class="number">0</span>; j &lt; c; j ++) &#123;</span><br><span class="line">        z[i][j] = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span>(<span class="type">int</span> k = <span class="number">0</span>; k &lt; b; k ++) &#123;</span><br><span class="line">            z[i][j] += x[i][k] * y[k][j];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure> 两个矩阵的基本元素乘法次数也显而易见了</p>
</blockquote>
<p>计算<span class="math inline">\(n\)</span>个矩阵序列的乘积<span
class="math inline">\(A_1 A_2\cdots
A_n\)</span>，矩阵规模保证能够合法相乘。</p>
<p>矩阵乘满足结合律，任何加括号方法计算结果相同。不同加括号方式，元素相乘次数不同。求一个矩阵乘法次序，使得元素相乘次数最少。</p>
<p>例：<span class="math inline">\(\langle A_1,A_2,A_3
\rangle\)</span>规模分别为<span class="math inline">\(10\times
100\)</span>、<span class="math inline">\(100\times 5\)</span>、<span
class="math inline">\(5\times 50\)</span></p>
<ul>
<li><span class="math inline">\(((A_1 A_2 ) A_3)\)</span>：<span
class="math inline">\(10\cdot 100\cdot 5+10\cdot 5\cdot
50=7500\)</span>次</li>
<li><span class="math inline">\((A_1 (A_2 A_3))\)</span>：<span
class="math inline">\(100\cdot 5\cdot 50+10\cdot 100\cdot
50=75000\)</span>次</li>
</ul>
<p><strong>最优子结构</strong>：</p>
<ul>
<li>最后一次矩阵乘法可以发生在任意位置<span
class="math inline">\(k\)</span>，即<span
class="math inline">\((A_1\cdots A_k)(A_{k+1}\cdots A_n)\)</span></li>
<li><span class="math inline">\(d(i,j)\)</span>：<span
class="math inline">\(A_i A_{i+1}\cdots A_{j-1}
A_j\)</span>这一区间的最优解</li>
<li>每一个<span
class="math inline">\(k\)</span>作为该区间最后一次乘法，都是潜在的最优方案</li>
<li>对应子问题为<span class="math inline">\(d(i,k)\)</span>与<span
class="math inline">\(d(k+1,j)\)</span></li>
</ul>
<p><strong>状态转移方程</strong>：</p>
<ul>
<li>设<span
class="math inline">\(p_0,p_1,\dots,p_n\)</span>是矩阵序列的规模，如<span
class="math inline">\(A_1\)</span>为<span
class="math inline">\(p_0\times p_i\)</span>，<span
class="math inline">\(A_i\)</span>为<span
class="math inline">\(p_{i-1}\times p_i\)</span></li>
<li><span class="math display">\[
d(i,j)=\begin{cases}
0 &amp; \text{如果}i=j \\
\min\limits_{i\leq k\leq j}\{d(i,k)+d(k+1,j)+p_{i-1}p_kp_j\} &amp;
\text{如果}i&lt;j
\end{cases}
\]</span></li>
</ul>
<img src="/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E7%9F%A9%E9%98%B5%E9%93%BE_%E6%9C%80%E5%90%8E%E4%B9%98%E6%B3%95%E4%BD%8D%E7%BD%AE.svg" class="" title="矩阵链_最后乘法位置">
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">DPS</span><span class="params">(<span class="type">int</span> l, <span class="type">int</span> r)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 基本情况：如果区间长度为1，不需要乘法</span></span><br><span class="line">    <span class="keyword">if</span>(l == r - <span class="number">1</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 使用引用减少重复代码，ans是dp[l][r]的引用，修改它就会修改dp[l][r]</span></span><br><span class="line">    <span class="type">int</span> &amp;ans = dp[l][r];</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 如果已经计算过，直接返回结果（记忆化）</span></span><br><span class="line">    <span class="keyword">if</span>(ans != <span class="number">-1</span>) <span class="keyword">return</span> ans;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 初始化：设置为一个足够大的值，表示无穷大</span></span><br><span class="line">    ans = <span class="number">0x3f3f3f3f</span>;   </span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 尝试所有可能的最后一次乘法位置</span></span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = l + <span class="number">1</span>; i &lt; r; i ++)</span><br><span class="line">        <span class="comment">// 状态转移：dp[l][r] = min(dp[l][i] + dp[i][r] + p[l]*p[i]*p[r])</span></span><br><span class="line">        <span class="comment">// 其中p[l]*p[i]*p[r]是最后一次乘法的代价</span></span><br><span class="line">        ans = std::<span class="built_in">min</span>(ans, <span class="built_in">DPS</span>(l, i) + <span class="built_in">DPS</span>(i, r) + p[l] * p[i] * p[r]);</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 返回区间[l,r]的最优解</span></span><br><span class="line">    <span class="keyword">return</span> ans;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>递推也可以写，分析计算顺序，大区间依赖小区间，那么按区间从小到大计算就可以写递推式DP了</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 初始化：单个矩阵不需要乘法，所以dp[i][i] = 0</span></span><br><span class="line"><span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">1</span>; i &lt;= n; i ++)</span><br><span class="line">    dp[i][i] = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 第一重循环：枚举子问题大小，从小到大处理子问题</span></span><br><span class="line"><span class="comment">// 从长度为2的区间开始，一直到长度为n的区间</span></span><br><span class="line"><span class="keyword">for</span>(<span class="type">int</span> len = <span class="number">2</span>; len &lt;= n; len ++) &#123;</span><br><span class="line">    <span class="comment">// 第二重循环：枚举子问题的起点</span></span><br><span class="line">    <span class="comment">// 对于每个长度，计算所有可能的起点</span></span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> l = <span class="number">1</span>; l &lt;= n - len + <span class="number">1</span>; l ++) &#123;</span><br><span class="line">        <span class="comment">// 计算子问题的终点</span></span><br><span class="line">        <span class="type">int</span> r = l + len - <span class="number">1</span>;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 初始化dp[l][r]为一种可能的方案：将第一个矩阵与剩余矩阵相乘</span></span><br><span class="line">        dp[l][r] = dp[l + <span class="number">1</span>][r] + <span class="number">1LL</span> * p[l - <span class="number">1</span>] * p[l] * p[r];</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 第三重循环：枚举最后一次矩阵乘法发生的位置</span></span><br><span class="line">        <span class="comment">// 尝试所有可能的切分点，找到最优解</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="type">int</span> i = l + <span class="number">1</span>; i &lt; r; i ++)</span><br><span class="line">            <span class="comment">// 状态转移：dp[l][r] = min(dp[l][i] + dp[i+1][r] + p[l-1]*p[i]*p[r])</span></span><br><span class="line">            <span class="comment">// 其中p[l-1]*p[i]*p[r]是最后一次乘法的代价</span></span><br><span class="line">            dp[l][r] = std::<span class="built_in">min</span>(</span><br><span class="line">                dp[l][r], </span><br><span class="line">                dp[l][i] + dp[i + <span class="number">1</span>][r] + p[l - <span class="number">1</span>] * p[i] * p[r]</span><br><span class="line">            );</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="背包dp">背包DP</h2>
<h3 id="例完全背包">例：完全背包</h3>
<p>有<span class="math inline">\(n\)</span>种物品，每种物品<span
class="math inline">\(i \in [1,n]\)</span>的重量<span
class="math inline">\(w_i\)</span>，价值<span
class="math inline">\(v_i\)</span>，数量不限。有一个背包可装总重不超过<span
class="math inline">\(b\)</span>的物品，求背包能装物品的最大总价值。</p>
<p>例：</p>
<p><span class="math inline">\(n=4\)</span>，<span
class="math inline">\(b=10\)</span></p>
<p><span class="math inline">\(v_1=1\)</span>，<span
class="math inline">\(v_2=3\)</span>，<span
class="math inline">\(v_3=6\)</span>，<span
class="math inline">\(v_4=9\)</span></p>
<p><span class="math inline">\(w_1=2\)</span>，<span
class="math inline">\(w_2=3\)</span>，<span
class="math inline">\(w_3=4\)</span>，<span
class="math inline">\(w_4=7\)</span></p>
<p><strong>最优子结构</strong>：</p>
<ul>
<li><span class="math inline">\(k\)</span>：只考虑前<span
class="math inline">\(k\)</span>种物品</li>
<li><span class="math inline">\(y\)</span>：背包装物品总重限制到<span
class="math inline">\(y\)</span> (<span class="math inline">\(y \leq
b\)</span>)</li>
<li><span class="math inline">\(d(k,y)\)</span>：前<span
class="math inline">\(k\)</span>种物品装入容量<span
class="math inline">\(y\)</span>的背包的最优解</li>
<li><span class="math inline">\(d(k,y)\)</span>只与<span
class="math inline">\(d(k,y-w_k)\)</span>和<span
class="math inline">\(d(k-1,y)\)</span>有关</li>
</ul>
<p><strong>状态转移方程</strong>：</p>
<ul>
<li><span class="math inline">\(d(k,y) = \max\{d(k,y-w_k)+v_k,
d(k-1,y)\}\)</span></li>
</ul>
<img src="/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E8%83%8C%E5%8C%85_%E5%AE%8C%E5%85%A8%E8%83%8C%E5%8C%85.svg" class="" title="完全背包">
<p><strong>直接DP</strong>：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="type">int</span> k = <span class="number">1</span>; k &lt;= n; k ++)</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> y = <span class="number">0</span>; y &lt;= b; y ++) &#123;</span><br><span class="line">        dp[k][y] = dp[k - <span class="number">1</span>][y];  <span class="comment">// 用前i-1种物品方案初始化前i种物品方案</span></span><br><span class="line">        <span class="keyword">if</span>(y &gt;= w[k])</span><br><span class="line">            dp[k][y] = std::<span class="built_in">max</span>(dp[k][y - w[k]] + v[k], dp[k - <span class="number">1</span>][y]);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p><span class="math inline">\(dp[i-1][\ldots]\)</span>只在计算<span
class="math inline">\(dp[i][\ldots]\)</span>时被用到，实际上并不需要二维数组。</p>
<p><strong>滚动数组优化</strong>：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="type">int</span> k = <span class="number">1</span>; k &lt;= n; k ++)</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> y = w[k]; y &lt;= b; y ++)</span><br><span class="line">        dp[y] = std::<span class="built_in">max</span>(dp[y - w[k]] + v[k], dp[y]);</span><br></pre></td></tr></table></figure>
<p><strong>滚动数组</strong>：</p>
<ul>
<li>重复在一个数组内计算不同信息，减少空间复杂度</li>
<li>确保未处理的信息不被覆盖</li>
</ul>
<p><strong>劣势</strong>：</p>
<ul>
<li>丢失了过程信息，无法还原完整方案</li>
</ul>
<h3 id="例01背包">例：01背包</h3>
<p>有<span class="math inline">\(n\)</span>个物品，每个物品<span
class="math inline">\(i \in [1,n]\)</span>的重量<span
class="math inline">\(w_i\)</span>，价值<span
class="math inline">\(v_i\)</span>（分别只有1个）。有一个背包可装总重不超过<span
class="math inline">\(b\)</span>的物品，求背包能装物品的最大总价值。</p>
<p><strong>最优子结构</strong>：</p>
<ul>
<li><span class="math inline">\(k\)</span>：只考虑前<span
class="math inline">\(k\)</span>种物品</li>
<li><span class="math inline">\(y\)</span>：背包装物品总重限制到<span
class="math inline">\(y\)</span> (<span class="math inline">\(y \leq
b\)</span>)</li>
<li><span class="math inline">\(d(k,y)\)</span>：前<span
class="math inline">\(k\)</span>种物品装入容量<span
class="math inline">\(y\)</span>的背包的最优解</li>
<li><span class="math inline">\(d(k,y)\)</span>只与<span
class="math inline">\(d(k-1,y-w_k)\)</span>和<span
class="math inline">\(d(k-1,y)\)</span>有关</li>
</ul>
<p><strong>状态转移方程</strong>：</p>
<ul>
<li><span class="math inline">\(d(k,y) = \max\{d(k-1,y-w_k)+v_k,
d(k-1,y)\}\)</span></li>
</ul>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="type">int</span> k = <span class="number">1</span>; k &lt;= n; k ++)</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> y = b; y &gt;= w[k]; y --)</span><br><span class="line">        dp[y] = std::<span class="built_in">max</span>(dp[y - w[k]] + v[k], dp[y]);</span><br></pre></td></tr></table></figure>
<img src="/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E8%83%8C%E5%8C%85_01%E8%83%8C%E5%8C%85.svg" class="" title="01背包">
<p><strong>其他背包问题</strong>：</p>
<ul>
<li>多重背包：每种物品有<span class="math inline">\(k_i\)</span>个</li>
<li>混合背包：有的1个，有的无限个，有的<span
class="math inline">\(k_i\)</span>个</li>
<li>二维背包：每个物品占<span
class="math inline">\(w_i\)</span>重量和<span
class="math inline">\(a_i\)</span>体积，重量体积都有上限</li>
</ul>
<p>背包是一类多阶段决策问题：每做一次决策就可以得到解的一部分。</p>
<p>经典资料参考：<a
target="_blank" rel="noopener" href="https://docs.qq.com/pdf/DRHdIcGltTllSVVVp">背包九讲</a></p>
<h2 id="线性结构dp">线性结构DP</h2>
<h3 id="例最长上升子序列">例：最长上升子序列</h3>
<p>给定<span class="math inline">\(n\)</span>个整数<span
class="math inline">\(A_1,A_2,\ldots,A_n\)</span>，找出最长的递增子序列。</p>
<p>例：1 5 3 6 9 8 10</p>
<p>最长上升子序列为：1&lt;3&lt;6&lt;9&lt;10</p>
<p><strong>最优子结构</strong>：</p>
<ul>
<li><span class="math inline">\(d(k)\)</span>：以第<span
class="math inline">\(k\)</span>个元素结尾的最长上升子序列长度</li>
<li><span class="math inline">\(d(k)\)</span>与<span
class="math inline">\(i&lt;k\)</span>的每个<span
class="math inline">\(d(i)\)</span>有关</li>
<li>对任意<span class="math inline">\(i&lt;k\)</span>，如果<span
class="math inline">\(A_i&lt;A_k\)</span>，则<span
class="math inline">\(A_k\)</span>续在以<span
class="math inline">\(A_i\)</span>结尾的子序列的后面</li>
</ul>
<p><strong>状态转移方程</strong>：</p>
<ul>
<li><span class="math inline">\(d(k) = \max\{d(i) | i&lt;k \text{且}
A_i&lt;A_k\} + 1\)</span></li>
</ul>
<img src="/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E6%9C%80%E9%95%BF%E4%B8%8A%E5%8D%87%E5%AD%90%E5%BA%8F%E5%88%97.svg" class="" title="最长上升子序列">
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> ans = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">for</span>(<span class="type">int</span> k = <span class="number">1</span>; k &lt;= n; k ++) &#123;</span><br><span class="line">    dp[k] = <span class="number">1</span>;  <span class="comment">// 至少自身有1的长度</span></span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> j = <span class="number">1</span>; j &lt; k; j ++)</span><br><span class="line">        <span class="keyword">if</span>(a[j] &lt; a[k] &amp;&amp; dp[j] + <span class="number">1</span> &gt; dp[k])</span><br><span class="line">            dp[k] = dp[j] + <span class="number">1</span>;</span><br><span class="line">    ans = std::<span class="built_in">max</span>(dp[k], ans);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>优化</strong>：</p>
<ol type="1">
<li>另存一个"尾元素"序列，表示各长度子序列的末尾元素</li>
<li>从左到右对每个数<span
class="math inline">\(X\)</span>在尾元素序列中二分查找不小于<span
class="math inline">\(X\)</span>的第一个<span
class="math inline">\(Y\)</span></li>
<li>如果找到：用<span class="math inline">\(X\)</span>替换<span
class="math inline">\(Y\)</span>，即该长度的子序列找到了更小的末尾元素</li>
<li>如果找不到：把<span
class="math inline">\(X\)</span>插入尾元素序列末尾，答案增长</li>
</ol>
<img src="/2025-04-16-26-%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E5%85%A5%E9%97%A8/%E6%9C%80%E9%95%BF%E4%B8%8A%E5%8D%87%E5%AD%90%E5%BA%8F%E5%88%97_%E5%B0%BE%E5%85%83%E7%B4%A0%E5%BA%8F%E5%88%97.svg" class="" title="最长上升子序列">
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> tlen = <span class="number">0</span>;   <span class="comment">// 尾元素个数，指向尾元素数组最后一个元素的下一个位置</span></span><br><span class="line"><span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; n; i ++) &#123;</span><br><span class="line">    <span class="type">int</span> ith = std::<span class="built_in">upper_bound</span>(b, b + tlen, a[i]) - b;  <span class="comment">// 找到不小于a[i]的第一个数</span></span><br><span class="line">    b[ith] = a[i];              <span class="comment">// 用a[i]替换找到的位置，没找到则ith就是末尾位置</span></span><br><span class="line">    <span class="keyword">if</span>(ith == tlen) tlen ++;    <span class="comment">// 没有不小于a[i]的数，长度增加</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="例最长公共子序列">例：最长公共子序列</h3>
<p>给两个序列<span class="math inline">\(A\)</span>和<span
class="math inline">\(B\)</span>，求长度最大的公共子序列。</p>
<p>例：</p>
<ul>
<li><span class="math inline">\(A\)</span>序列：1,3,2,8,6,5,7</li>
<li><span class="math inline">\(B\)</span>序列：2,1,4,8,5,7,9</li>
</ul>
<p>最长公共子序列长度是4，即2,8,5,7</p>
<p><strong>最优子结构</strong>：</p>
<ul>
<li><span class="math inline">\(d(i,j)\)</span>：<span
class="math inline">\(A\)</span>的前<span
class="math inline">\(i\)</span>个元素与<span
class="math inline">\(B\)</span>的前<span
class="math inline">\(j\)</span>个元素的LCS</li>
<li>与<span class="math inline">\(d(i-1,j-1)\)</span>、<span
class="math inline">\(d(i,j-1)\)</span>、<span
class="math inline">\(d(i-1,j)\)</span>有关：考察<span
class="math inline">\(A_i\)</span>与<span
class="math inline">\(B_j\)</span>是否相等</li>
<li>如果<span class="math inline">\(A_i=B_j\)</span>，<span
class="math inline">\(A_i\)</span>与<span
class="math inline">\(B_j\)</span>配对一定可以作为<span
class="math inline">\(d(i,j)\)</span>的一个解的结尾</li>
<li>如果<span class="math inline">\(A_i \neq B_j\)</span>，那么<span
class="math inline">\(d(i,j)\)</span>的解一定是<span
class="math inline">\(d(i-1,j)\)</span>和<span
class="math inline">\(d(i,j-1)\)</span>的其中一个</li>
</ul>
<p><strong>状态转移方程</strong>：</p>
<ul>
<li><span class="math inline">\(d(i,j) = \begin{cases} d(i-1,j-1)+1
&amp; \text{若}A_i=B_j \\ \max(d(i,j-1), d(i-1,j)) &amp; \text{若}A_i
\neq B_j \end{cases}\)</span></li>
</ul>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">LCS</span><span class="params">(<span class="type">char</span> a[], <span class="type">int</span> alen, <span class="type">char</span> b[], <span class="type">int</span> blen)</span> </span>&#123;</span><br><span class="line">    dp[<span class="number">0</span>][<span class="number">0</span>] = dp[<span class="number">0</span>][<span class="number">1</span>] = dp[<span class="number">1</span>][<span class="number">0</span>] = <span class="number">0</span>;     <span class="comment">// 假设a、b下标从1开始</span></span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">1</span>; i &lt;= alen; i ++) &#123;       <span class="comment">// a的游标</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="type">int</span> j = <span class="number">1</span>; j &lt;= blen; j ++) &#123;   <span class="comment">// b的游标</span></span><br><span class="line">            <span class="keyword">if</span>(a[i] == b[j]) &#123;</span><br><span class="line">                <span class="comment">// a[i] == b[j]时，加入a的前i-1、b的前j-1的LCS</span></span><br><span class="line">                dp[i][j] = dp[i - <span class="number">1</span>][j - <span class="number">1</span>] + <span class="number">1</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">// a[i] != b[j]时，从另外两个子问题较大的转移</span></span><br><span class="line">                dp[i][j] = std::<span class="built_in">max</span>(dp[i - <span class="number">1</span>][j], dp[i][j - <span class="number">1</span>]);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> dp[alen][blen];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="其它dp前瞻">其它DP前瞻</h2>
<h3 id="状态压缩dp">状态压缩DP</h3>
<p>将子问题当作"状态"，状态转移方程就是状态的变化。把描述子问题的"状态"压缩为一个整数，优化状态转移效率。</p>
<p><strong>例题：互不侵犯</strong></p>
<p><span class="math inline">\(N \times N\)</span>的棋盘放置<span
class="math inline">\(K\)</span>个国王，国王攻击范围为周围8个格子。多少种摆放方案，能够互相不在攻击范围。</p>
<p><span class="math inline">\(d(i,j,l)\)</span>：前<span
class="math inline">\(i\)</span>行，第<span
class="math inline">\(i\)</span>行状态为<span
class="math inline">\(j\)</span>，已放置<span
class="math inline">\(l\)</span>个国王的方案数。 <span
class="math inline">\(j\)</span>就是压缩的状态：0~8格子有/没有国王是一个01串，用<span
class="math inline">\(int\)</span>表示。</p>
<p>状态压缩示意图（<span class="math inline">\(j=41_{(10)} =
101001_{(2)}\)</span>）： <figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">+---+---+---+---+---+---+</span><br><span class="line">| 1 | 0 | 1 | 0 | 0 | 1 |</span><br><span class="line">+---+---+---+---+---+---+</span><br><span class="line">| K |   | K |   |   | K |</span><br><span class="line">+---+---+---+---+---+---+</span><br></pre></td></tr></table></figure>
其中K表示放置国王，空格表示不放置国王。这个二进制数101001表示在第1、3、6列放置国王。</p>
<h3 id="数位dp">数位DP</h3>
<p>统计满足一定条件的数的数量，把数字拆解一位一位地用DP处理。</p>
<p><strong>例题：数字计数</strong></p>
<p>给定两个正整数<span class="math inline">\(a,b\)</span>，求<span
class="math inline">\([a,b]\)</span>范围内各数位0~9各出现多少次。</p>
<p>假设<span
class="math inline">\(d(i)\)</span>统计"1"出现的次数（0~9次数都相等）：
<span class="math inline">\(d(i) = d(i-1) \times 10 +
10^{i-1}\)</span>，然后做进一步作后续处理……</p>
<h3 id="树形dp">树形DP</h3>
<p>在树结构上DP。</p>
<p><strong>例题：树上的最远点对</strong></p>
<p><span
class="math inline">\(n\)</span>个结点的树，找两个点，它们的距离最远。</p>
<p><span class="math inline">\(d(i)\)</span>：节点<span
class="math inline">\(i\)</span>的子树中根到叶子的最大距离。 <span
class="math inline">\(d(i) = \max\{d(j)\} + 1\)</span>，<span
class="math inline">\(j\)</span>为<span
class="math inline">\(i\)</span>的子节点。 所有<span
class="math inline">\(d(j)\)</span>最大的<span
class="math inline">\(j=u\)</span>和<span
class="math inline">\(j=v\)</span>，<span
class="math inline">\(d(u)+d(v)+2\)</span>为答案。</p>
<h3 id="轮廓线dp插头dp">轮廓线DP（插头DP）</h3>
<p>轮廓线DP是一种处理网格类问题的动态规划方法，特别适用于需要记录连通性信息的场景。其核心思想是沿着网格的轮廓线进行状态转移，通过记录轮廓线上每个格子的"插头"状态（如是否有路径经过、路径的方向等）来压缩状态空间。插头DP常用于解决哈密顿回路、路径覆盖、连通性等问题，如"回路计数"、"棋盘覆盖"等经典问题。通过巧妙的状态设计和转移规则，插头DP能够高效处理看似复杂的状态转移，是解决特定类型网格问题的重要工具。</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/ACM/" rel="tag"># ACM</a>
              <a href="/tags/Algorithm/" rel="tag"># Algorithm</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2025-04-05-25-%E5%80%8D%E5%A2%9E%E4%B8%8E%E7%A8%80%E7%96%8F%E8%A1%A8/" rel="prev" title="25.倍增与稀疏表">
                  <i class="fa fa-angle-left"></i> 25.倍增与稀疏表
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2025-04-23-27-%E5%88%86%E6%94%AF%E9%99%90%E7%95%8C%E4%B8%8E%E5%89%AA%E6%9E%9D/" rel="next" title="27.分支限界与剪枝">
                  27.分支限界与剪枝 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments utterances-container"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">CSGrandeur</span>
  </div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://fastly.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://fastly.jsdelivr.net/npm/@next-theme/pjax@0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/sidebar.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://fastly.jsdelivr.net/npm/hexo-generator-searchdb@1.4.1/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>







  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://fastly.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


<script class="next-config" data-name="utterances" type="application/json">{"enable":true,"repo":"CSGrandeur/csgrandeur.github.io","issue_term":"pathname","theme":"github-light"}</script>
<script src="/js/third-party/comments/utterances.js"></script>

</body>
</html>
